package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.SinaNewsDownloader;
import com.spider.silence.utils.PropertiesUtil;

import java.util.LinkedList;

/**
 * @author Administrator
 * @description 描述
 * @time 2017/4/12 0012
 */
public class SinaNewsDownloaderPool {
    private static SinaNewsDownloaderPool instance= new SinaNewsDownloaderPool();
    protected LinkedList<SinaNewsDownloader> pool = Lists.newLinkedList();

    private SinaNewsDownloaderPool(){
        int initNum= Integer.parseInt(PropertiesUtil.getVal("SinaNews.DownLoader.Pool.initNum"));
        //KaiDiDownLoader downLoader =new KaiDiDownLoader();
        //downLoader.init();
        for(int i=0;i<initNum;i++) {
            SinaNewsDownloader sinaNewsDownloader = new SinaNewsDownloader();
            pool.add(sinaNewsDownloader);
        }
    }

    public  static SinaNewsDownloaderPool getInstance(){
        if(instance==null){
            instance=new SinaNewsDownloaderPool();
        }
        return  instance;
    }
    public  void releaseDownLoader(SinaNewsDownloader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }

    public SinaNewsDownloader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                SinaNewsDownloader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }

    /**
     * 清空池
     */
    public void empty(){
        pool= Lists.newLinkedList();
    }

}
